package com.lw.leetcode.arr.b;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/29 11:05
 */
public class GetDistances {    public long[] getDistances(int[] arr) {
    int length = arr.length;
    HashMap<Integer, List<Integer>> map = new HashMap<>(length, 1);
    for (int i = 0; i < length; i++) {
        map.computeIfAbsent(arr[i], v -> new ArrayList<>()).add(i);
    }
    long[] ans = new long[length];
    for (List<Integer> p : map.values()) {
        long sum = 0L;
        for (int i : p) {
            sum += i - p.get(0);
        }
        ans[p.get(0)] = sum;
        for (int i = 1, n = p.size(); i < n; i++) {
            sum += (2L * i - n) * (p.get(i) - p.get(i - 1));
            ans[p.get(i)] = sum;
        }
    }
    return ans;
}
}
